/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.Response;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

/**
 * 注册
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP注册接口")
public class AppRegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserDao userDao;

    @PostMapping("register")
    @ApiOperation("注册")
    public ResponseEntity<Response> register(@Valid @RequestBody RegisterForm form, BindingResult bindingResult) {
        // 表单校验
        ValidatorUtils.validateEntity(form);
        UserEntity existingUser = userDao.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getIPhone,form.getIPhone()));
        UserEntity existingUser2 = userDao.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getID,form.getID()));
        Response response = new Response();
        if (bindingResult.hasErrors()) {
            // 如果有错误，构建一个包含错误信息的响应
            response.setCode(400);
            response.setMessage(bindingResult.getFieldError().getDefaultMessage());
            return ResponseEntity.badRequest().body(response);
        }
        if (existingUser != null || existingUser2 != null ||userService.queryByOpenid(form.getOpenId()) != null) {
            // 如果找到了已存在的用户或已存在相同的openid，则返回错误响应
            response.setCode(404);
            response.setMessage("该手机号或身份证号或openid已被注册");
            return ResponseEntity.badRequest().body(response);
        }
        UserEntity user = new UserEntity();
        user.setIPhone(form.getIPhone());  // 手机号
        user.setID(form.getID());
        user.setOpenId(form.getOpenId());
        user.setClassification(form.getClassification());
        userService.save(user);

        // 构建响应对象
        response.setCode(0);
        response.setMessage("注册成功");
        response.setData(user);

        // 返回响应
        return ResponseEntity.ok(response);
    }
}

